package com.situ.day37;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDemo {

    @Test
    public void testClass() throws ClassNotFoundException{
        //1.Class.forName
        Class clazz1 = Class.forName("com.situ.day37.Student");
        //2.类型.class
        Class clazz2 = Student.class;
        //3.对象.getClass()
        //Student student = new Student();
        //Class clazz3 = student.getClass();

        //System.out.println(clazz1 == clazz2);//true
        //System.out.println(clazz1 == clazz3);//true
    }

    @Test
    public void testConstructor1() {
        Class clazz = Student.class;
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
            System.out.println(constructor.getName());//构造方法名字
            System.out.println(constructor.getModifiers());//修饰符
        }
    }

    @Test
    public void testConstructor2() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class clazz = Student.class;
        //private Student(Integer id, String name, Integer age, String gender)
        Constructor constructor = clazz.getDeclaredConstructor(Integer.class, String .class, Integer.class, String.class);
        //java.lang.IllegalAccessException: class com.situ.day37.ReflectDemo cannot access a member of class com.situ.day37.Student with modifiers "private"
        constructor.setAccessible(true);
        //Student student = new Student(1, "zhangsan", 23, "男");
        Student student = (Student) constructor.newInstance(1, "zhangsan", 23, "男");
        System.out.println(student);
    }

    @Test
    public void testMethod()throws ClassNotFoundException, NoSuchMethodException,InvocationTargetException, InstantiationException,IllegalAccessException {
        //Student student = new Student();
        //student.setName("zhangsan");
        Class clazz = Class.forName("com.situ.day37.Student");
        Constructor constructor = clazz.getDeclaredConstructor();
        Student student = (Student) constructor.newInstance();
        //student.setName("zhangsan");
        Method method = clazz.getDeclaredMethod("setName", String.class);
        method.invoke(student,"zhansgan");
        System.out.println(student);
    }
}
